const axios = require('axios')
const config = require('./AuthConfig')

const {client_id, client_secret} = config.github

module.exports = (server) => {
  server.use( async (ctx, next) => {
    if (ctx.path === '/auth'){
      const code = ctx.query.code
      if(!code) {
        ctx.body = 'code not exsit'
        return
      }
      const result = await axios({
        method: 'POST',
        url: 'https://github.com/login/oauth/access_token',
        data: {
          client_id,
          client_secret,
          code
        },
        headers: {
          Accept: 'application/json',
        }
      })
      if( result.status === 200 && (result.data && !result.data.error)) {
        ctx.session.githubAuth = result.data
        const { access_token,token_type} = result.data
        const userInfoResp = await axios({
          method: 'GET',
          url: 'https://api.github.com/user',
          headers: {
            'Authorization': `${token_type} ${access_token}`
          }
        })
        ctx.session.userInfo = userInfoResp.data
        //重定向前看session是否有urlBeforeAuth 路径，否则重定向根目录
        ctx.redirect((ctx.session && ctx.session.urlBeforeAuth)||'/')
        ctx.session.urlBeforeAuth = ''
      } else {
        const errorMsg = result.data.error
        ctx.body = `requst token failed: ${errorMsg} `
      }
    } else {
      await  next()
    }
  })
}
